"""Update local ut"""
import csv
import time
from pathlib import Path
from ut import UT


class FileIdentifyError(Exception):
    def __init__(self, file_name):
        self.name = file_name

    def __str__(self):
        return f'Error: {self.name} was not identified'


# ut格式 [(name, type, ut)]
class Update:
    def __init__(self):
        self.current_ut_content = []

    # 格式化时间字符串 yyyy/mm/dd hh:mm:ss
    @staticmethod
    def _format_time_str(float_time: float) -> str:
        ftd = {}
        for num in range(60):
            if num < 10:
                ftd[num] = f'0{num}'
            else:
                ftd[num] = f'{num}'
        struct_time = time.localtime(float_time)
        return f'{struct_time.tm_year}/{ftd[struct_time.tm_mon]}/{ftd[struct_time.tm_mday]} ' \
               f'{ftd[struct_time.tm_hour]}:{ftd[struct_time.tm_min]}:{ftd[struct_time.tm_sec]}'

    # 遍历文件
    def _iter_tree(self, folder: Path):
        for file in folder.iterdir():
            if file.name == 'updated_time.csv':
                continue
            if file.is_dir():
                self.current_ut_content.append(UT(file.name, 'folder', self._format_time_str(file.stat().st_mtime)))
                self._iter_tree(file)
            elif file.is_file():
                self.current_ut_content.append(UT(file.name, 'file', self._format_time_str(file.stat().st_mtime)))
            else:
                raise FileIdentifyError(file.name)

    # 读取文件信息并修改时间
    def _read_files(self):
        root = Path('D:\\SYNC')
        try:
            self._iter_tree(root)
        except Exception as error:
            if isinstance(error, FileIdentifyError):
                print(error)
            else:
                print('Error: ', error)

    # 生成csv文件
    def _create(self):
        with open('D:\\SYNC\\updated.csv', 'w', newline='', encoding='utf-8') as file:
            csv.writer(file).writerows(self.current_ut_content)

    # 入口函数
    def run(self):
        try:
            if Path('D:\\SYNC\\updated.time/csv').exists():
                self._read_files()
            else:
                self._create()
        except Exception as error:
            print('Error: ', error)
